package com.cxcy.swustlearner.utils;

//import cn.hutool.core.util.StrUtil;
//import com.example.qing.mapper.UserMapper;
//import com.example.qing.pojo.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletRequestAttributeEvent;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.swing.*;
import java.util.Date;
import java.util.Map;
@Component
@Slf4j
public class JwtUtils {

    private static String signKey = "itheima_cxcy";
    private static Long expire = 43200000L;//12小时
//    private static UserMapper staticUserMapper;
//    @Resource
//    UserMapper userMapper;
//
//    @PostConstruct
//    public void setUserService(){
//        staticUserMapper=userMapper;
//    }
//    /**
//     * 生成JWT令牌
//     * @param claims JWT第二部分负载 payload 中存储的内容
//     * @return
//     */

    public  String generateJwt(Map<String, Object> claims){
        String jwt = Jwts.builder()
                .addClaims(claims)
                .signWith(SignatureAlgorithm.HS256, signKey)
                .setExpiration(new Date(System.currentTimeMillis() + expire))
                .compact();
        return jwt;
    }

    /**
     * 解析JWT令牌
     * @param jwt JWT令牌
     * @return JWT第二部分负载 payload 中存储的内容
     */
    public static Claims parseJWT(String jwt){
        Claims claims = Jwts.parser()
                .setSigningKey(signKey)
                .parseClaimsJws(jwt)
                .getBody();
        return claims;
    }

//    public static User getCurrentUser(){
//        try {
//            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            String token = request.getHeader("token");
//            if (StrUtil.isNotBlank(token)) {
//                Claims claims = Jwts.parser()
//                        .setSigningKey(signKey)
//                        .parseClaimsJws(token)
//                        .getBody();
//                int id = claims.get("id", Integer.class);
//                return staticUserMapper.selectById(Integer.valueOf(id));
//            }
//        } catch (Exception e) {
//            return null;
//        }
//        return null;
//    }
}
